package android.FiltrosJava;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;
import java.awt.image.WritableRaster;

public class Pointllize extends AbstractImageBasic{
	protected int rad;
	
	public Pointllize(int radius){
		setRadius(radius);
	}
	
	public void setRadius(int radius){		
		rad = radius;					
		if (rad < 2)
			rad = 2;		
	}
    /*
	public BufferedImage applyFilter(BufferedImage src) {
		Graphics2D g2d = src.createGraphics();
		Graphics2D g2dst = null; 
		BufferedImage dst = null;			
		
		int x, y, px, py;
		int dimX = src.getWidth();
		int dimY = src.getHeight();
		WritableRaster rasterDst = null;
		int[] cor = new int[3];
		
		y = 0;
		while(y < dimY){
			x = 0;
			while(x < dimX){
				if ((x + rad) < dimX)
					px = rad;
				else
					px = dimX - x -1;
					
				if ((y + rad) < dimY)
					py = rad;
				else
					py = dimY - y -1;
				
				dst = src.getSubimage(x, y, px, py);
				g2dst = dst.createGraphics();
				rasterDst = dst.getRaster();
				cor = computeMeanColor(rasterDst, 0, 0, px, py);
				g2dst.fillRect(0,0,px,py);
				g2dst.setPaint(new Color(cor[0], cor[1], cor[2]));
				g2dst.fill(new Ellipse2D.Double(0, 0, px, py));				
				g2dst.dispose();				
				g2d.drawImage(dst,null,x,y);
								
				x += rad;
			}
			y += rad;
		}		

		return src;		
    }*/
	
	//*
	public BufferedImage applyFilter(BufferedImage dst) {
		BufferedImage src = copiaImagem(dst);
		Graphics2D g2d = dst.createGraphics();
					
		int x, y;
		int dimX = src.getWidth();
		int dimY = src.getHeight();
		WritableRaster raster = src.getRaster();   	    	
		int[] cor = new int[3];
		g2d.fillRect(0, 0, dimX, dimY);
		
		y = 0;
		while(y < dimY){
			x = 0;
			while(x < dimX){
				cor = computeMeanColor(raster, x, y, dimX, dimY);
				g2d.setPaint(new Color(cor[0], cor[1], cor[2]));
				g2d.fill(new Ellipse2D.Double(x, y, rad, rad));			
								
				x += rad;
			}
			y += rad;
		}		
		src = null;
		return dst;		
    }
	//*/
	
	protected int[] computeMeanColor(WritableRaster raster, int px, int py, int dimX, int dimY){
		int[] cor = new int[3];
		int[] imageData = new int[raster.getNumBands()];
		int rx, ry;
		cor[0] = 0;
		cor[1] = 0;
		cor[2] = 0;
		
		for (int z = 0; z < 10; z++){
			rx = (int) (px + (Math.random() * (2 * rad - 1)));
			ry = (int) (py + (Math.random() * (2 * rad - 1)));
			
			if (rx < 0)
				rx = 0;
			
			if (rx >= dimX)
				rx = dimX -1;
				
			if (ry < 0)
				ry = 0;
			
			if (ry >= dimY)
				ry = dimY -1;
			
			raster.getPixel(rx,ry,imageData);
			cor[0] += imageData[0];
			cor[1] += imageData[1];
			cor[2] += imageData[2];												
		}
		
		cor[0] = (int) (cor[0] / 10);
		cor[1] = (int) (cor[1] / 10);
		cor[2] = (int) (cor[2] / 10);
		
		return cor;
	}	
}
